package com.dzx.permissionmanagersystem.exception;

import com.dzx.permissionmanagersystem.common.JsonData;
import lombok.extern.slf4j.Slf4j;



import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
public class ExceptionHandler implements HandlerExceptionResolver {


    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        String url = httpServletRequest.getRequestURL().toString();
        ModelAndView modelAndView;
        String defaultMsg = "System error"; //默认错误信息
        JsonData jsonData ;
           if(e instanceof  PermissionException){
                jsonData = JsonData.fail(e.getMessage());
           }else {
               log.error("unknow exception,url:"+url,e);
                jsonData = JsonData.fail(defaultMsg);
           }
        modelAndView = new ModelAndView("exception",jsonData.toMap());
        modelAndView.addObject("url",url);

//        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//        HttpSession httpSession = request.getSession();
        return modelAndView;
    }
}
